package com.bangyo.website.manager.impl;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.bangyo.website.Website;
import com.bangyo.website.manager.WebsiteManager;
import com.bangyo.website.searcher.WebsiteSearcher;

public class WebsiteManagerImpl implements WebsiteManager
{
    private final Log logger = LogFactory.getLog(WebsiteManagerImpl.class);

    private final static Map<String, List<Pattern[]>> websitePatterns = new HashMap<String, List<Pattern[]>>();

    private static boolean initialized = false;

    private WebsiteSearcher websiteSearcher = null;

    public void reloadWebsite()
    {
        List<Website> websiteList = websiteSearcher.list();
        for (Website site:websiteList)
        {
            try
            {
                String domain = site.getDomain().toLowerCase();
                if (!websitePatterns.containsKey(domain))
                {
                    websitePatterns.put(domain, new ArrayList<Pattern[]>(5));
                }
                websitePatterns.get(domain).add(
                    new Pattern[]
                    {
                        Pattern.compile(site.getUriRegex()),
                        Pattern.compile(site.getVideoRegex())
                    });
            }
            catch (PatternSyntaxException e)
            {
                if (logger.isWarnEnabled())
                {
                    logger.warn("error compile uri regex: ", e);
                }
            }
        }
        initialized = true;
    }

    private List<Pattern[]> findWebsitePattern(String host)
    {
        String h = host.toLowerCase();
        for (String domain:websitePatterns.keySet())
        {
            if (null!=h&&h.endsWith(domain))
            {
                return websitePatterns.get(domain);
            }
        }
        return null;
    }

    public Pattern resolve(URL url)
    {
        if (!initialized)
        {
            reloadWebsite();
        }
        List<Pattern[]> patternList = findWebsitePattern(url.getHost());
        if (null==patternList)
        {
            if (logger.isDebugEnabled())
            {
                logger.debug("can not find website with domain["+url.getHost()
                    +"].");
            }
            return null;
        }
        for (Pattern[] patterns:patternList)
        {
            if (patterns[0].matcher(url.getFile()).matches())
            {
                return patterns[1];
            }
        }
        if (logger.isDebugEnabled())
        {
            logger.debug("can't find pattern matches url["+url+"].");
        }
        return null;
    }

    public void setWebsiteSearcher(WebsiteSearcher websiteSearcher)
    {
        this.websiteSearcher = websiteSearcher;
    }

}
